import axios from "axios";
import qs from "querystring";
import { message } from "antd";
import nprogress from "nprogress";
import store from "../redux/store";
import { createDeleteUserInfoAction } from "../redux/action_creators/login_action";
import "nprogress/nprogress.css";

const instance = axios.create({
  timeout: 5000,
});

instance.interceptors.request.use(
  (config) => {
    // console.log({ config });
    nprogress.start();
    const token = store.getState().userInfo.token;
    if (token) {
      config.headers.Authorization = token;
    }
    const { method, data } = config;
    if (method.toLocaleLowerCase() === "post") {
      if (data instanceof Object) {
        config.data = qs.stringify(data);
      }
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

instance.interceptors.response.use(
  (res) => {
    nprogress.done();
    return res;
  },
  (err) => {
    nprogress.done();
    if (err.response.status === 401) {
      message.error("身份失败,重新登陆", 1);
      return store.dispatch(createDeleteUserInfoAction());
    }
    message.error(err.message);
    // Promise.reject(err)
    // console.log("in", err);
    // return new Promise(() => {});
  }
);

export default instance;
